package org.calzz.jajb.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.calzz.jajb.JsonDeserializer;
import org.calzz.jajb.JsonSerializer;
import org.calzz.jajb.io.IWriter;
import org.springframework.core.MethodParameter;

/**
 * The default converter for dates. By default it uses
 * <code>SimpleDateFormat</code> and the default pattern, which can be easily
 * changed through the constructor.
 * 
 * @author Marek Brodziak <marek.brodziak@gmail.com>
 * @author Piotr Pejas <piotr.pejas@gmail.com>
 * @since Feb 6, 2008
 */
public class DateConverter implements IConverter {

	private static final String ROOT_DATE_PATTERN = "EEE MMM dd HH:mm:ss zzz yyyy";

	private Log log = LogFactory.getLog(DateConverter.class);

	private SimpleDateFormat formatter;

	public DateConverter() {
		formatter = new SimpleDateFormat(ROOT_DATE_PATTERN, Locale.ROOT);
	}

	/**
	 * @param pattern a specific pattern to use
	 */
	public DateConverter(String pattern) {
		this.formatter = new SimpleDateFormat(pattern, Locale.ROOT);
	}

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#canConvert(java.lang.Class)
	 */
	public boolean canConvert(Class<?> clazz) {
		return Date.class.equals(clazz);
	}

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#marshal(java.lang.Object,
	 *      java.lang.String, org.jamjam.jajb.io.IWriter,
	 *      org.jamjam.jajb.JsonSerializer)
	 */
	public void marshal(Object obj, String name, IWriter writer, JsonSerializer serializer) {
		writer.writeKey(name);
		writer.writeString(formatter.format(obj));
	}

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#unmarshal(java.lang.Object,
	 *      java.lang.Class, org.jamjam.jajb.JsonDeserializer)
	 */
	public <T> Object unmarshal(Object env, Class<T> clazz, JsonDeserializer deserializer, MethodParameter methodParam) {
		String unescaped = env.toString();
		unescaped = unescaped.substring(1, unescaped.length() - 1);

		try {
			return formatter.parse(unescaped);
		} catch (ParseException e) {
			log.error(e);
			return null;
		}
	}
}
